package util

import (
	"crypto/md5"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"konglu-pay/global"
	"os"
)

// RSA加密
func RsaEncrypt(plainText []byte, path string) []byte {
	//打开文件
	file, err := os.Open(path)
	if err != nil {
		global.Log.Errorf("file open error: %v", err)
		return nil
	}
	defer func(file *os.File) {
		_ = file.Close()
	}(file)
	//读取文件的内容
	info, _ := file.Stat()
	buf := make([]byte, info.Size())
	_, _ = file.Read(buf)
	//pem解码
	block, _ := pem.Decode(buf)
	//x509解码
	publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		global.Log.Errorf("parse public key error: %v", err)
		return nil
	}
	//类型断言
	publicKey := publicKeyInterface.(*rsa.PublicKey)
	//对明文进行加密
	cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
	if err != nil {
		global.Log.Errorf("encrypt key error: %v", err)
		return nil
	}
	//返回密文
	return cipherText
}

// RSA解密
func RsaDecrypt(cipherText []byte, path string) []byte {
	//打开文件
	file, err := os.Open(path)
	if err != nil {
		global.Log.Errorf("file open error: %v", err)
		return nil
	}
	defer func(file *os.File) {
		_ = file.Close()
	}(file)
	//获取文件内容
	info, _ := file.Stat()
	buf := make([]byte, info.Size())
	_, _ = file.Read(buf)
	//pem解码
	block, _ := pem.Decode(buf)
	//X509解码
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		global.Log.Errorf("parse private key error: %v", err)
		return nil
	}
	//对密文进行解密
	plainText, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
	if err != nil {
		global.Log.Errorf("decrypt key error: %v", err)
		return nil
	}
	//返回明文
	return plainText
}

func MD5(str string) string {
	data := []byte(str) //切片
	has := md5.Sum(data)
	md5str := fmt.Sprintf("%x", has) //将[]byte转成16进制
	return md5str
}
